const express=require('express');
const url =require('url');
let router_index=express.Router()
// router.get
router_index.get('/',(req,res)=>{
    // 分页
    let {page}=req.query;
    const size=2;
    
    page = parseInt(page)
    if(isNaN(page) || page<1){
        page=1;
    }else if(!/^[1-9]\d*$/.test(page)){
        page=1;
    }
    let start=(page-1)*size;
    

    req.db.query(`SELECT ID,title,sub_title,position_main,position_second,property_types,area_min,area_max,ave_price,main_img_real_path FROM house_table LIMIT ${start},${size}`,(err,house_data)=>{
        if(err){
            res.sendStatus(500);
        }else{
            req.db.query('SELECT COUNT(*) AS c FROM house_table',(err,data)=>{
                if(err){
                    res.sendStatus(500);
                }else{
                    let all_page_num=Math.ceil(data[0].c / size);
                    let previous_page = page<=1?1:page-1;
                    let next_page = page>=all_page_num?all_page_num:page-0+1;
                    res.render('list',{
                        data:house_data,
                        show_page_count: 7,
                        all_page_num,
                        cur_page: page,
                        previous_page,
                        next_page

                    })
                }
            })
            
        }
    })
})
//防止图片盗链

router_index.get('/static_img/:img_path',(req,res)=>{
    let {img_path}=req.params;
    let obj=url.parse(req.headers['referer']);
    if(obj.host!='localhost:8080'){
        res.sendStatus(404);
    }else{
        console.log(req.cwd)
        res.sendFile(`${req.cwd}\\upload\\${img_path}`);
    }
})


router_index.get('/detail/:id',(req,res)=>{
    let {id}=req.params;

    req.db.query(`SELECT * FROM house_table WHERE ID='${id}'`,(err,data)=>{
        if(err){
            res.sendStatus(500)
        }else{
            res.render('detail',{data:data[0]});
        }
    })
})




module.exports=router_index;